package com.tjetc.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tjetc.common.Result;
import com.tjetc.domain.Otc;
import com.tjetc.service.OtcService;
import com.tjetc.service.impl.OtcServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

@WebServlet("/otc/*")
@MultipartConfig
public class OtcServlet extends HttpServlet {
    private OtcService otcService = new OtcServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        try {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer rid = Integer.valueOf(request.getParameter("rid"));
        Integer mid = Integer.valueOf(request.getParameter("mid"));
        System.out.println("mid = " + mid);
        Integer num = Integer.valueOf(request.getParameter("num"));
        String name = request.getParameter("name");
        String remarks = request.getParameter("remarks");
        Otc otc = new Otc();
        otc.setRid(rid);
        otc.setMid(mid);
        otc.setNum(num);
        otc.setName(name);
        otc.setRemarks(remarks);
        boolean b = otcService.add(otc);
        if (b){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success("开药铺成功"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("开药失败，出异常喽！"));
    }
}
